package com.gin.kotlin.no_gay_alliance.adapter

import android.content.Context
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.TextView
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.AbstractPagerListActivity.Companion.floatButtonPagerOnclick
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument.Type
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.databinding.ItemTopicBinding
import com.gin.kotlin.no_gay_alliance.fragment.topiclist.ColListFragment
import com.gin.kotlin.no_gay_alliance.fragment.topiclist.ForumListFragment
import com.gin.kotlin.no_gay_alliance.model.TopicStatusModel
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils.Companion.zdtIntoTextView
import com.gin.nga.enums.EntranceType
import com.gin.nga.enums.status.ReplyStatus
import com.gin.nga.response.topic.TopicInfo
import java.util.Locale

/**
 * 主题列表适配器
 * @property checkable 是否显示复选框(仅收藏夹显示)
 * @property hideForumName 是否隐藏版面名称(合集中隐藏)
 * @property selected 已选中的主题(收藏夹)
 * @constructor
 */
class TopicListAdapter(
    context: Context,
    handler: MyHandler,
    private val checkable: Boolean = false,
    private val hideForumName: Boolean = false,
) : AbstractBindingRecyclerViewAdapter<ItemTopicBinding, TopicInfo>(context, handler), View.OnLongClickListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    val selected: MutableList<TopicInfo> = mutableListOf()

    /**
     * 当显示某一位置的item时的操作
     * @param holder ViewHolder
     * @param position Int
     * @param b ViewBinding
     * @param dataModel 数据对象
     */
    override fun onBindViewHolder(holder: ViewHolder<ItemTopicBinding>, position: Int, b: ItemTopicBinding, dataModel: TopicInfo) {
        // 点击事件
        b.root.setOnClickListener(this)
        b.root.setOnLongClickListener(this)
        b.root.tag = dataModel

        // 主题标题
        b.tvTopicTitle.text = dataModel.title
        // 默认颜色
        b.tvTopicTitle.setTextColor(getAttrColor(R.attr.textColor))

        configTopicTitleFont(b.tvTopicTitle,dataModel.getTopicStatus())

        // 版面名称
        b.tvForumName.text = dataModel.topicParent?.name?.let { "[$it]" }
        b.tvForumName.visibility = if (hideForumName) View.GONE else View.VISIBLE
        // 作者名称
        b.tvAuthorName.text = dataModel.authorName

        // 匿名ico
        val authorIcon = if (dataModel.getStatus()?.contains(ReplyStatus.ANONYMOUS) == true) R.drawable.ic_person_anonymous_16
        else R.drawable.ic_person_18
        b.tvAuthorName.setCompoundDrawablesWithIntrinsicBounds(getDrawable(authorIcon), null, null, null)

        b.tvLastPosterName.text = String.format(Locale.CHINESE, "%s(%d)", dataModel.lastPosterName, dataModel.replies)

        //  主题状态
        b.tvTopicStatus.text = SpannableStringBuilder().also { builder ->
            TopicStatusModel.parse(dataModel).forEach { status ->
                val text = String.format(Locale.CHINESE, "[%s]", status.name)
                builder.append(text)
                val span = ForegroundColorSpan(getAttrColor(status.color))
                builder.setSpan(span, builder.length - text.length, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

            // 镜像
            dataModel.quoteFromTopicId?.takeIf { it > 0 }?.also {
                val text = "[镜像]"
                builder.append(text)
                val span = ForegroundColorSpan(getAttrColor(R.attr.textColorBlue))
                builder.setSpan(span, builder.length - text.length, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

        }
        b.tvTopicStatus.visibility = if (b.tvTopicStatus.text.isEmpty()) View.GONE else View.VISIBLE

        val defaultTextColor = getAttrColor(R.attr.textColor)

        //  发帖时间文字，颜色
        dataModel.postDatetime?.also { zdtIntoTextView(context, it, b.tvPostTime, defaultTextColor) }
        //  最后回复时间文字，颜色
        dataModel.lastPost?.also { zdtIntoTextView(context, it, b.tvLastPostTime, defaultTextColor) }

        // 主题内回复

        b.tvUserReply.visibility = if (dataModel.reply != null) View.VISIBLE else View.GONE
        b.layoutContent.removeAllViews()
        dataModel.reply?.also { reply ->
            reply.postDatetime?.also { zdtIntoTextView(context, it, b.tvUserReplyTime, defaultTextColor) }
            // 显示回复内容
            val tv = TextView(context).also { it.text = reply.content?.replace("<br/>", "\n") }
            b.layoutContent.addView(tv)
        }

        // 收藏夹专用
        b.checkBox.visibility = if (checkable) View.VISIBLE else View.GONE
        b.checkBox.setOnCheckedChangeListener(null)
        b.checkBox.isChecked = selected.contains(dataModel)
        b.checkBox.tag = dataModel
        b.checkBox.setOnCheckedChangeListener(this)
    }


    override fun onLongClick(v: View?): Boolean {
        val dataModel = v?.tag as? TopicInfo ?: return false
        // 长按打开最后一页
        val topicId = dataModel.getEntranceId() ?: return false
        val totalPage = dataModel.getTotalPage() ?: return false
        val id = dataModel.getEntranceId() ?: return false
        val argument = ReplyListArgument(Type.LIST, topicId = topicId, totalPage = totalPage)
        // 根据全局配置决定弹窗 ，或直接打开最后一页
        if (GlobalProperty.getInstance().showPagerDialog) {
            val currentPage = App.INSTANCE.database.topicHistoryDao().get(id)?.page ?: 1
            floatButtonPagerOnclick(context, currentPage, totalPage) { page ->
                // 选定页数时
                ReplyListActivity.startActivity(context, argument.copy(targetPage = page))
            }
        } else {
            ReplyListActivity.startActivity(context, argument.copy(targetPage = totalPage))
        }

        return true
    }

    override fun onClick(v: View?) {
        val dataModel = v?.tag as? TopicInfo ?: return
        val title = dataModel.title ?: return
        val id = dataModel.getEntranceId() ?: return
        val type = dataModel.getEntranceType()
        val total = dataModel.replies?.plus(1)
        val replyId = dataModel.reply?.replyId

        // 用户回复,单回复模式打开
        if (replyId != null) {
            ReplyListActivity.startActivity(context, ReplyListArgument(Type.SINGLE, replyId = dataModel.reply?.replyId))
        } else when (type) {
            EntranceType.TOPIC -> {
                val topicId = dataModel.topicId ?:return
                // 浏览历史
                val topicHistory = App.INSTANCE.database.topicHistoryDao().get(topicId)
                val totalPage = dataModel.getTotalPage()?.coerceAtLeast(topicHistory?.totalPage ?: 0)
                // 参数
                val argument = ReplyListArgument(
                    Type.LIST,
                    topicId = topicId,
                    title = title,
                    totalPage = totalPage,
                    total = total,
                    replyId = dataModel.reply?.replyId,
                    hostId = dataModel.authorUid ?: topicHistory?.authorId,
                )

                // 如果无历史，直接打开
                if (topicHistory == null) {
                    Log.i(TAG, "打开主题: $topicId $title, 楼主：${dataModel.authorUid}")
                    ReplyListActivity.startActivity(context, argument)
                } else {
                    val targetPage = if (GlobalProperty.getInstance().openHistoryPage) topicHistory.page else 1
                    println("targetPage = $targetPage")
                    ReplyListActivity.startActivity(context, argument.copy(targetPage = targetPage))
                }
            }

            EntranceType.FORUM -> {
                Log.i(TAG, "打开版面: $id $title")
                ForumListFragment.startActivity(context, id, title = title)
            }

            EntranceType.COL -> {
                Log.i(TAG, "打开合集: $id $title")
                ColListFragment.startActivity(context, id, title = title)
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        val dataModel = buttonView?.tag as? TopicInfo ?: return
        if (isChecked) {
            selected.add(dataModel)
        } else {
            selected.remove(dataModel)
        }
    }
}